package com.hr.service;

import com.hr.dao.MenuDAO;
import com.hr.dto.JsonResp;
import com.hr.model.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

//
@Service
@CacheConfig(cacheNames = "menus_cache")
public class MenuService
{
    @Autowired
    MenuDAO menuDAO;


    public List<Menu> getMenusByCId(int cid) {

        Position curPos = null;
        boolean isAdmin=false;

        Archive archive=((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getArchive();
        if(archive!=null)
        {
            List<Position> positions=archive.getPositions();
            for(Position position: positions)
            {
                if(position.getCompany()==null)
                    continue;
                if(position.getCompany().getId()==0&&position.getPrivilege().equals("管理"))
                {
                    isAdmin=true;
                    break;
                }
                else if(position.getCompany().getId()==cid)
                    curPos=position;
            }
        }
        List<Menu> menus=new ArrayList<>();

        for(Menu menu: menuDAO.getMasterMenu().getChildren())
        {
            if (isAdmin||menu.getRequire()==null)
                menus.add(menu);
            else if (curPos==null||curPos.getPrivilege()==null)
                continue;
            else if(menu.getRequire().equals(curPos.getPrivilege()))
                menus.add(menu);
        }

        return menus;
    }



    public List<Menu> getMenusByParentId(int parentId)
    {
        return menuDAO.getMenusByParentId(parentId);
    }


    @Cacheable
    public List<Menu> getAllMenus() {
        return menuDAO.getAllMenus();
    }

    public Menu getMenuByMId(int mid)
    {
        return menuDAO.getMenuByMId(mid);
    }

//    @Transactional
//    public boolean updateMenuRole(Integer rid, Integer[] mids) {
//        menuRoleMapper.deleteByRid(rid);
//        if (mids == null || mids.length == 0) {
//            return true;
//        }
//        Integer result = menuRoleMapper.insertRecord(rid, mids);
//        return result==mids.length;
//    }
}
